package com.example.app.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.app.common.Result;
import com.example.app.common.PageResult;
import com.example.application.MenuService;
import com.example.infra.po.MenuPo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/menus")
@RequiredArgsConstructor
public class AdminMenuController {

    private final MenuService menuService;

    @GetMapping
    public Result<List<MenuPo>> list(@RequestParam(value = "title", required = false) String title) {
        LambdaQueryWrapper<MenuPo> qw = new LambdaQueryWrapper<>();
        if (title != null && !title.isEmpty()) {
            qw.like(MenuPo::getTitle, title);
        }
        return Result.success(menuService.list(qw));
    }

    @GetMapping("/page")
    public Result<PageResult<MenuPo>> page(
            @RequestParam(value = "page", defaultValue = "1") Long pageNum,
            @RequestParam(value = "size", defaultValue = "10") Long pageSize,
            @RequestParam(value = "title", required = false) String title) {
        LambdaQueryWrapper<MenuPo> qw = new LambdaQueryWrapper<>();
        if (title != null && !title.isEmpty()) {
            qw.like(MenuPo::getTitle, title);
        }
        Page<MenuPo> page = new Page<>(pageNum, pageSize);
        menuService.page(page, qw);
        return Result.success(PageResult.of(page));
    }

    @PostMapping
    public Result<Boolean> create(@RequestBody MenuPo menu) {
        return Result.success(menuService.save(menu));
    }

    @PutMapping("/{id}")
    public Result<Boolean> update(@PathVariable Integer id, @RequestBody MenuPo menu) {
        menu.setId(id);
        return Result.success(menuService.updateById(menu));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> remove(@PathVariable Integer id) {
        return Result.success(menuService.removeById(id));
    }
}


